package com.broada.apm.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipException;

import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;  

  
  
public class ZipUtil {  
      
    /** 
     * @param src：要压缩的目录 
     * @param dest：压缩文件存档 
     * @throws Exception 
     */  
    public static void zip(String src, String dest, List filter) throws Exception {  
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(dest));  
        File srcFile = new File(src);  
        zip(out,srcFile,"",filter);  
        out.close();  
    }  
      
    /** 
     * @param out 
     * @param srcFile 
     * @param base：根路径 
     * @param filter：过滤 
     * @throws Exception 
     */  
    public static void zip(ZipOutputStream out, File srcFile, String base, List filter) throws Exception {  
        if(srcFile.exists()==false) {  
            throw new Exception("压缩目录不存在!");  
        }  
          
        if(srcFile.isDirectory()) {  
            File[] files = srcFile.listFiles();  
            for(int i=0; i<files.length; i++) {  
                zip(out,files[i],base + files[i].getName(),filter);  
            }  
        } else {  
            if (isExist(base, filter)) {  
                base = base.length() == 0 ? srcFile.getName() : base ;  
                ZipEntry zipEntry = new ZipEntry(base);  
                out.putNextEntry(zipEntry);  
                FileInputStream in = new FileInputStream(srcFile);  
                int length = 0;  
                byte[] b = new byte[1024];  
                while((length=in.read(b,0,1024))!=-1) {  
                    out.write(b,0,length);  
                }  
                in.close();  
            }  
        }  
    }  
      
    /** 
     * 过滤出要压缩的文件夹 
     * @param base 
     * @param list 
     * @return 
     */  
    public static boolean isExist(String base, List list) {  
        if (list != null && !list.isEmpty()) {  
            for (int i = 0; i < list.size(); i++) {  
                if (base.indexOf((String) list.get(i)) >= 0) {  
                    return true;  
                }  
            }  
        }  
        return true;  
    }  
      
    /** 
     * @param srcFile：压缩文件路径 
     * @param dest：解压到的目录 
     * @param deleteFile：解压完成后是否删除文件 
     * @throws Exception 
     */  
    public static void unZip(String srcFile,String dest,boolean deleteFile, boolean tempPath)  throws Exception {  
        File file = new File(srcFile);  
        File destdir = new File(dest);
        unzip(file, destdir, deleteFile, tempPath);  
    }

		public static void unzip(File file, File destdir,boolean deleteFile, boolean tempPath) throws IOException, Exception, ZipException,
				FileNotFoundException {
			File lastVersionFile = new File(destdir.getPath());
			if (!tempPath) {
				if (!destdir.exists()) {
					destdir.mkdirs();
				} else {
					// 当文件夹已存在时，新建一个
					destdir = new File(destdir.getPath() + System.currentTimeMillis());
				} 
			} else {
				if (!destdir.exists()) {
					destdir.mkdirs();
				}
			}

			ZipFile zipFile = new ZipFile(file);  
			if(!file.exists()) {  
				throw new Exception("解压文件不存在!");  
			}  
			
			Enumeration e = zipFile.getEntries();  
			while(e.hasMoreElements()) {  
			    ZipEntry zipEntry = (ZipEntry)e.nextElement();  
			    if(zipEntry.isDirectory()) {  
			        String name = zipEntry.getName();  
			        name = name.substring(0,name.length()-1);  
			        File f = new File(destdir , name);  
			        f.mkdirs();  
			    } else if ("logo.png".equals(zipEntry.getName())) {
			    	File logoFile = new File(lastVersionFile, zipEntry.getName());  
			    	logoFile.getParentFile().mkdirs();  
			    	logoFile.createNewFile();  
			        InputStream logoIs = zipFile.getInputStream(zipEntry);  
			        FileOutputStream logoFos = new FileOutputStream(logoFile);
			        IOUtils.copy(logoIs, logoFos);
			        IOUtils.closeQuietly(logoIs);
			        IOUtils.closeQuietly(logoFos);
			        
			        File f = new File(destdir, zipEntry.getName());  
			        f.getParentFile().mkdirs();  
			        f.createNewFile();  
			        InputStream is = zipFile.getInputStream(zipEntry);  
			        FileOutputStream fos = new FileOutputStream(f);
			        IOUtils.copy(is, fos);
			        IOUtils.closeQuietly(is);
			        IOUtils.closeQuietly(fos);
			    } else {  
			        File f = new File(destdir, zipEntry.getName());  
			        f.getParentFile().mkdirs();  
			        f.createNewFile();  
			        InputStream is = zipFile.getInputStream(zipEntry);  
			        FileOutputStream fos = new FileOutputStream(f);
			        IOUtils.copy(is, fos);
			        IOUtils.closeQuietly(is);
			        IOUtils.closeQuietly(fos);
			    }  
			}  
			  
			if (zipFile != null) {  
			    zipFile.close();  
			}  
			  
			if(deleteFile) {  
			    file.delete();  
			}
		}  
      
    /** 
     * 获取Zip文件的注释信息 
     * @param srcFile 
     * @return 
     */  
    public static String getZipComment(String srcFile) {  
        String comment = "";  
        try {  
            ZipFile zipFile = new ZipFile(srcFile);  
            Enumeration e = zipFile.getEntries();  
  
            while (e.hasMoreElements()) {  
                ZipEntry ze = (ZipEntry) e.nextElement();  
  
                comment = ze.getComment();  
                if (comment != null && !comment.equals("")  
                        && !comment.equals("null")) {  
                    break;  
                }  
            }  
  
            zipFile.close();  
        } catch (Exception e) {  
            System.out.println("获取zip文件注释信息失败:" + e.getMessage());  
        }  
  
        return comment;  
    }  
} 